package restful

import (
	v1 "gitee.com/lcc_dr/restful-api-demo/api/book/v1"
	"gitee.com/lcc_dr/restful-api-demo/apps"
	"gitee.com/lcc_dr/restful-api-demo/apps/book/impl"
	restfulspec "github.com/emicklei/go-restful-openapi"
	"github.com/emicklei/go-restful/v3"
	"github.com/go-playground/validator/v10"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"
)

var RestImpl = &HandleRestService{}
var validate *validator.Validate

//定义 gin handler 数据结构
type HandleRestService struct {
	l logger.Logger

	svc v1.ServiceServer
}

func NewHandleRestService() *HandleRestService {

	return &HandleRestService{}
}

// 从IOC注册中心获BookService 实例
func (h *HandleRestService) Config() {

	// h.svc = apps.HostService
	h.svc = apps.GetBookImpl(impl.AppName).(v1.ServiceServer)
	h.l = zap.L().Named("restful")

}

func (H *HandleRestService) Name() string {
	return impl.AppName
}

// 从IOC注册中心获HostService 实例
func (u *HandleRestService) Registry(ws *restful.WebService) {

	// ws := new(restful.WebService)
	ws.
		Path("/book").
		Consumes(restful.MIME_XML, restful.MIME_JSON).
		Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well

	tags := []string{"book"}

	ws.Route(ws.GET("/").To(u.QueryBook).
		// docs
		Doc("get all users").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Reads(v1.QueryBookRequest{}).
		Writes(v1.Book{}).
		Returns(200, "OK", v1.BookSet{}))

	ws.Route(ws.GET("/{user-id}").To(u.DescribeBook).
		// docs
		Doc("get a user").
		Param(ws.PathParameter("user-id", "identifier of the user").DataType("integer").DefaultValue("1")).
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Reads(v1.DescribeBookRequest{}). // on the response
		Writes(v1.Book{}).
		Returns(200, "OK", v1.DescribeBookRequest{}).
		Returns(404, "Not Found", nil))

	ws.Route(ws.PUT("/{user-id}").To(u.UpdateBook).
		// docs
		Doc("update a user").
		Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")).
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Reads(v1.DescribeBookRequest{})) // from the request

	ws.Route(ws.POST("").To(u.CreateBook).
		// docs
		Doc("create a user").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Reads(v1.CreateBookRequest{})) // from the request

	ws.Route(ws.DELETE("/{user-id}").To(u.DeleteBook).
		// docs
		Doc("delete a user").
		Metadata(restfulspec.KeyOpenAPITags, tags).
		Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")))

	// u.rsc = resc.Add(ws)

}

// func (H *HandleBookService) Registry(g *grpc.Server) {

// }
func init() {

	apps.RegistryRestful(RestImpl)
}
